<template>
  <el-form ref="loginFormRef" :model="formData" :rules="loginRules" label-width="80px" class="login-form">
    <!-- 手机号 -->
    <el-form-item prop="phone" label="手机" class="login-form-item">
      <el-input v-model="formData.phone" type="text" placeholder="请输入手机号" clearable>
        <template #prefix>
          <el-icon class="el-input__icon"><Phone /></el-icon>
        </template>
      </el-input>
    </el-form-item>

    <!-- 密码 -->
    <el-form-item prop="password" label="密码" class="login-form-item">
      <el-input
        v-model="formData.password"
        type="password"
        placeholder="请输入密码"
        class="text-14px text-#333 w-90%"
        show-password
        clearable
      >
        <template #prefix>
          <el-icon class="el-input__icon"><Lock /></el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { Phone, Lock } from '@element-plus/icons-vue'

// 定义 props
const props = defineProps<{
  formData: {
    phone: string
    password: string
  }
}>()

// 定义 emits
const emit = defineEmits<{
  'update:formData': [value: { phone: string; password: string }]
  'validate': [isValid: boolean]
}>()

// 表单引用
const loginFormRef = ref()

// 手机号正则
const PhoneReg = /^1[3-9]\d{9}$/

// 登录表单校验规则
const loginRules = reactive({
  phone: [
    { required: true, message: '请填写手机号', trigger: 'blur' },
    { pattern: PhoneReg, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请填写密码', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' }
  ]
})

// 监听表单数据变化
const updateFormData = () => {
  emit('update:formData', { ...props.formData })
}

// 暴露校验方法给父组件
const validate = async () => {
  if (!loginFormRef.value) return false
  try {
    await loginFormRef.value.validate()
    emit('validate', true)
    return true
  } catch {
    emit('validate', false)
    return false
  }
}

// 暴露方法给父组件
defineExpose({
  validate
})
</script>

<style scoped lang="scss">
.login-form {
  .login-form-item {
    margin-bottom: 15px;

    .el-form-item__label {
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }

    .el-form-item__content {
      display: block;
    }

    .el-form-item__error {
      color: #ff4444;
      font-size: 12px;
      padding-top: 4px;
      position: static;
      margin-top: 4px;
    }

    .el-input {
      width: 100%;
      max-width: 450px;

      .el-input__wrapper {
        height: 48px;
        padding: 0 15px;
        border-radius: 4px;
      }

      .el-input__inner {
        height: 48px;
        line-height: 48px;
        font-size: 16px;
      }
    }
  }
}
</style>
